package com.notepad.util;

import com.notepad.R;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.widget.Toast;

/**
 * 双击退出
 */
public class DoubleClickExitHelper {
	private final Activity mActivity;
	private Toast mBackToast;
	private Handler mHandler;
	private boolean isOnKeyBacking;
	public DoubleClickExitHelper(Activity activity) {
		mActivity = activity;
		mHandler = new Handler(Looper.getMainLooper());

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode != KeyEvent.KEYCODE_BACK){
			return false;
		}
		if(isOnKeyBacking){
			mHandler.removeCallbacks(onBackRunnable);
			if(mBackToast != null){
				mBackToast.cancel();
			}
			mActivity.finish();
			return true;
		}else{
			isOnKeyBacking = true;
			if(mBackToast == null){
				mBackToast = Toast.makeText(mActivity, R.string.double_back_hint, 2000);
			}
			mBackToast.show();
			mHandler.postDelayed(onBackRunnable, 2000);
			return true;
		}
			
	}
	
	private Runnable onBackRunnable = new Runnable() {
		
		@Override
		public void run() {
			isOnKeyBacking = false;
			if(mBackToast != null){
				mBackToast.cancel();
			}
		}
	};
	
}
